/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Grid.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
qui(
    function (require, exports, module) {

        Statistic.Grid = function (options) {
            this.dao = Statistic.Dao;
            this.config = Statistic.Config;
            this.options = options || {};
            this.exportExcel = false;
        };
        Com.inherits(Statistic.Grid, Ancestor.Grid).extend({
            produceDataRun: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.$form = self.options.$form;
                self.$hiddenGrid = self.options.$hiddenGrid;
                self.$logGrid = self.options.$logGrid;
                var taskArr = [];
                var task = {
                    regName: "legoChannelId",
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.redirect,
                        dataType: "json",
                        data: {"request": JSON.stringify({url: Statistic.Constant.thirdUrl_channel_type, type: "get", params: {size: 100}, needCookie: true}), timeSign: new Date().getTime()}
                    }
                };
                taskArr.push(task);
                taskArr.push( EpgWeb.Task.getConfigType(self.dao.cfgName.LogType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.initSuggest();
                    self.startGrid();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            startGrid: function () {
                var self = this;
                self.initQueryDate();
                self.bindBasicEvent();
                self.initDlg();
                self.initGrid();
                self.initLogGrid();
            },
            initDlg:function(){
                $("#vodEpisodeLogDiv").dialog({
                    title: "历史记录",
                    autoOpen: false,
                    width: 900,
                    height: 600,
                    modal: true,
                    dialogClass: 'alert'
                });
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            initGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                self.$grid.jqGrid(gridConfig);
                self.echoQuery();
            },

            initLogGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LOG);
                self.$logGrid.jqGrid(gridConfig);
            },

            checkBeforeQuery: function (params) {
                var sMinsStr = typeof params.sPrMins == "string";
                var eMinsStr = typeof params.ePrMins == "string";
                if (sMinsStr && params.sPrMins.length > 0 && !EpgWeb.Plugin.Validate.checkNum(params.sPrMins)) {
                    EpgWeb.Plugin.showTips({type: "error", content: "节目时长需要非负整数"})
                    return false;
                }
                if (eMinsStr && params.ePrMins.length > 0 && !EpgWeb.Plugin.Validate.checkNum(params.ePrMins)) {
                    EpgWeb.Plugin.showTips({type: "error", content: "节目时长需要非负整数"})
                    return false;
                }

                if ((params.sPrMins + "").length > 0 && (params.ePrMins + "").length > 0) {
                    if (parseInt(params.ePrMins) <= parseInt(params.sPrMins)) {
                        EpgWeb.Plugin.showTips({type: "error", content: "节目时长范围错误"})
                        return false;
                    }
                }
                return true;
            },
            getParam: function () {
                var self = this;
                var params = {};
                params.cname = $("input[name=cname]").val();
                var $form = self.options.$form;
                var sPrMins = $("input[name=sPrMins]").val();
                var ePrMins = $("input[name=ePrMins]").val();
                params.sPrMins = sPrMins;
                params.ePrMins = ePrMins;
                if (EpgWeb.Plugin.Validate.checkNum(sPrMins)) {
                    params.sPrMins = parseInt(sPrMins) * 60;
                }
                if (EpgWeb.Plugin.Validate.checkNum(ePrMins)) {
                    params.ePrMins = parseInt(ePrMins) * 60;
                }
                var $elements = $.makeArray($form.prop('elements')).filter(function () {
                    return true; //this.name;
                });
                var filterNameArr = ["cname", "sPrMins", "ePrMins"];
                $.each($elements, function (i, element) {
                    if (element.type == "text") {
                        if (filterNameArr.indexOf(element.name) == -1) {
                            params[element.name] = $.trim($(element).val()) || '';
                        }
                    }
                });
                params.type = "pd";
                params.ocrFlag = $("select[name=is_ocr_flag]").val();
                params.ocrTitleFlag = $("select[name=is_ocr_title_flag]").val();
                //ocrTitleFlag
                return params;
            },
            initQueryDate: function () {
                var currentDate = new Date(), beginDateTime = new Date(), endDateTime = new Date();
                Statistic.Util.setZeroTime(currentDate);
                endDateTime.setTime(currentDate.getTime() + 86400000);
                beginDateTime.setTime(endDateTime.getTime() - 7 * 86400000);
                var searchBegin = Statistic.Util.formatDateTimeFormat(beginDateTime);
                var searchEnd = Statistic.Util.formatDateTimeFormat(endDateTime);
                Statistic.Util.bindDate("b_date", "e_date", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchBegin, minDateTime: new Date(searchBegin.replace(/-/g, "/")) });
                $("input[name=e_date]").datetimepicker("setDate", endDateTime);
                $("input[name=b_date]").datetimepicker("setDate", beginDateTime);

                Statistic.Util.bindDate("live_b_date", "live_e_date", { maxDate: searchEnd, maxDateTime: new Date(searchEnd.replace(/-/g, "/")), minDate: searchBegin, minDateTime: new Date(searchBegin.replace(/-/g, "/")) });
                $("input[name=live_e_date]").datetimepicker("setDate", endDateTime);
                $("input[name=live_b_date]").datetimepicker("setDate", beginDateTime);
            },
            bindBasicEvent: function () {
                var self = this;
                var $container = self.options.$container;
                $container.find("button.query-btn").bind("click", function (event) {
                    self.query();
                    return false;
                })
                $container.find("button.query-excel").bind("click", function (event) {
                    self.$hiddenGrid.html("");
                    $("button.query-excel").prop("disabled", "disabled")
                    self.doExportExcel();
                })
                $container.find("button[name=resetBtn]").bind("click", function (event) {
                    self.$form[0].reset();
                    self.initQueryDate();
                })
            },
            doExportExcel: function () {
                var self = this;
                var params = self.getParam();
                if (!self.checkBeforeQuery(params)) {
                    return;
                }
                params.pageSize = 5000;
                self.dao.getExportDataAll(params, {
                    lockHandler: function () {
                        $("button.query-excel").prop("disabled", "disabled")
                    },
                    flushCheck: function (curNum) {
                        return curNum >= 5000
                    },
                    phaseHandler: function (dataArr, fileName) {
                        self.doExportExcelAllCallBack(dataArr, fileName);
                    },
                    unlockHandler: function () {
                        $("button.query-excel").removeAttr("disabled")
                    }
                });
            },
            doExportExcelAllCallBack: function (dataArr, fileName) {
                var self = this
                if (dataArr != null && dataArr.length > 0) {
                    self.$hiddenGrid.append(Statistic.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(dataArr, function (i, element) {
                        self.$hiddenGrid.append(Statistic.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                if (fileName != null) {
                    EpgWeb.Plugin.tableToExcel({nodeType: true, innerHTML: self.$hiddenGrid.html()}, fileName)
                    //    self.$hiddenGrid.tableToExcel({name: fileName});
                } else {
                    EpgWeb.Plugin.tableToExcel({nodeType: true, innerHTML: self.$hiddenGrid.html()}, "制作数据统计")
                    // self.$hiddenGrid.tableToExcel();
                }
                self.$hiddenGrid.html("");
            },
            doExportExcelCallBack: function (data) {
                var self = this
                if (data != null && data.data.result.length > 0) {
                    self.$hiddenGrid.append(Statistic.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(data.data.result, function (i, element) {
                        self.$hiddenGrid.append(Statistic.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                //      self.$hiddenGrid.tableToExcel();
                EpgWeb.Plugin.tableToExcel({nodeType: true, innerHTML: self.$hiddenGrid.html()}, "制作数据统计")
                self.$hiddenGrid.html("");
                console.log("excel build end");
                $("button.query-excel").removeAttr("disabled")
            },
            echoQuery: function () {
                var self = this;
                self.query();
            },
            query: function () {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                if (!self.checkBeforeQuery(params)) {
                    return;
                }
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    mtype: 'get',
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },
            initSuggest: function () {
                var self = this;
                var channelTypeSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        renderPanel: function (handler) {
                            self.dao.getChannelType(handler)
                        },
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {size: 100} : {word: term, size: 100}
                            var requestData = {url: Statistic.Constant.thirdUrl_channel_type, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["name"];
                                itemData["value"] = item["name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            return item["label"];
                        }
                    }
                }

                $("input[name=cname]").suggest(channelTypeSuggest.options);
                $("input[name=cname]").suggest("setSelectedItem", null);

                var prNameSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: EpgWeb.Constant.thirdUrl_video_url, type: "get", params: {word: term, type: "properTitle"}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["entityId"];
                                itemData[options.labelKey] = item["properTitle"];
                                itemData[self._displayKey] = item["entityId"];
                                itemData["channelName"] = item["channelName"];
                                itemData["globalPublishDate"] = item["globalPublishDate"] || "";
                                itemData["isPurchase"] = item["isPurchase"];
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                ret.push(itemData);
                            });
                            return ret;
                        },

                        template: function (item) {
                            var formatArr = [];
                            formatArr.push('<span class="contract-width100">' + item["id"] + '</span>');
                            formatArr.push('<span class="contract-width150">' + item["label"] + '</span>');
                            formatArr.push('<span class="contract-width60">' + item["channelName"] + '</span>');
                            formatArr.push('<span class="contract-width120">' + item.globalPublishDate + '</span>');
                            formatArr.push('<span class="contract-width80">' + Statistic.Util.formatter.purchase(item.isPurchase) + '</span>');
                            formatArr.push('<span class="contract-width80">' + Statistic.Util.formatter.publishStatus(item.pagePublishStatus) + '</span>');
                            return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                        },
                        header: '<div class="contract-item" >' +
                            '<span class="contract-width100">节目Id</span>' +
                            '<span class="contract-width150">节目显示名称</span>' +
                            '<span class="contract-width60">频道</span>' +
                            '<span class="contract-width120">发行时间</span>' +
                            '<span class="contract-width80">是否付费</span>' +
                            '<span class="contract-width80">发布状态</span></div>'
                    }
                };

                $("input[name=pr_name]").suggest(prNameSuggest.options);


                var fuzzyQuerySuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Statistic.urlConfig.queryChannelName, type: "get", params: {keyword: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === 200) {
                                data = json.response.list == null ? null : json.response.list;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["channel_name"];
                                itemData[options.labelKey] = item["channel_name"];
                                itemData[self._displayKey] = item["channel_name"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item["id"];
                        }
                    }
                }
                $("input[name=cp]").suggest(fuzzyQuerySuggest.options);

                var emailSuggest = {
                    options: {
                        source: EpgWeb.urlConfig.redirect,
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: Statistic.Constant.thirdUrl_query_user, type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"]
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=u]").suggest(emailSuggest.options);
            }


        })
    }
);